package com.villaday.idf.custom;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.AppContext;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.model.house_materialEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ShareUtilse;
import com.villaday.idf.util.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static android.content.Context.CLIPBOARD_SERVICE;


/**
 * 填写邀请码对话框
 */
@SuppressLint("ValidFragment")
public class VipSvipLijiyaoqingDialog extends BaseDialog implements View.OnClickListener {


    private static String poster;
    private final Context context;
    private ArrayList<String> imgUrls;
    public static String IMAGE_NAME = "iv_share_";

    public static int i = 0;
    private LoadingDialog loadingDialog;
    private List<String> imgs;
    private String des;

    public static VipSvipLijiyaoqingDialog newInstance(Context context, List<String> imgUrls, String poster,String des) {
        VipSvipLijiyaoqingDialog.poster = poster;
        VipSvipLijiyaoqingDialog dialog = new VipSvipLijiyaoqingDialog(context);
        Bundle bundle = new Bundle();
        bundle.putStringArrayList("imgUrls", (ArrayList<String>) imgUrls);
        bundle.putString("des",des);
        dialog.setArguments(bundle);
        return dialog;
    }

    public VipSvipLijiyaoqingDialog(Context context) {
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window window = getDialog().getWindow();
        View view = inflater.inflate(R.layout.dialog_vip_svip,
                ((ViewGroup) window.findViewById(android.R.id.content)), false);


        //必须设置，否则不能全屏
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //宽度撑满
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.BOTTOM);
        //进入退出动画
        window.setWindowAnimations(R.style.animTranslateBottom);
        getDialog().setCancelable(true);
        getDialog().setCanceledOnTouchOutside(true);
        ImageView close = view.findViewById(R.id.iv_close_dialog);
        close.setOnClickListener(this);
        TextView tv_wx = view.findViewById(R.id.tv_wx);
        tv_wx.setOnClickListener(this);
        TextView tv_pyq = view.findViewById(R.id.tv_pyq);
        tv_pyq.setOnClickListener(this);
        TextView tv_save = view.findViewById(R.id.tv_save);
        tv_save.setOnClickListener(this);


        final ImageView img = view.findViewById(R.id.img);

        imgUrls = getArguments().getStringArrayList("imgUrls");
        des = getArguments().getString("des");

        if (imgUrls != null && imgUrls.size() > 0) {
            final RequestOptions options = new RequestOptions()
                    .error(R.drawable.ic_replace_0)
                    .fitCenter()
                    .placeholder(R.drawable.ic_replace_0);
            LogeUtil.e("dddd", (imgUrls.get(0)));
            Glide.with(context).asBitmap().apply(options).load(poster).into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {

                    int width = resource.getWidth();
                    int height = resource.getHeight();
                    if (height > PhoneUtil.dp2px(context, 330)) {
                        img.getLayoutParams().width = height / width * PhoneUtil.dp2px(context, 330);
                        img.getLayoutParams().height = PhoneUtil.dp2px(context, 330);
                    } else {
                        img.getLayoutParams().width = width;

                        img.getLayoutParams().height = height;
                    }
                    img.requestLayout();
                    img.setImageBitmap(resource);

                }


            });
        }


        return view;
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {


            case R.id.iv_close_dialog:
                dismiss();
                break;
            case R.id.tv_wx: {//微信
                ClipboardManager mClipboardManager = mClipboardManager =
                        (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);

                ClipData mClipData;
                mClipData = ClipData.newPlainText("test", des);
                mClipboardManager.setPrimaryClip(mClipData);
                ToastUtil.initToast(context, "文案已复制");
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                List<String> list = new ArrayList<>();
                list.clear();
               /* boolean isEQPposter = false;
                for (int j = 0; j < imgUrls.size(); j++) {
                    if (imgUrls.get(j).equals(poster)) {
                        isEQPposter = true;
                    }
                }
                if (!isEQPposter) {
                    list.add(poster);

                }


                if (imgUrls.size() > 8) {
                    for (int j = 0; j < 8; j++) {
                        list.add(imgUrls.get(j));
                    }

                } else {
                    list.addAll(imgUrls);
                }*/
                list.add(poster);

                ShareUtilse.shareImage(context, 0, list, list.get(list.size() - 1),des);
                dismissLoading();

            }
            break;
            case R.id.tv_pyq: {//朋友圈
                ClipboardManager mClipboardManager = mClipboardManager =
                        (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);

                ClipData mClipData;
                mClipData = ClipData.newPlainText("test", des);
                mClipboardManager.setPrimaryClip(mClipData);
                ToastUtil.initToast(context, "文案已复制");

                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                List<String> list1 = new ArrayList<>();
                list1.clear();
                boolean isEQPposter = false;
                for (int j = 0; j < imgUrls.size(); j++) {
                    if (imgUrls.get(j).equals(poster)) {
                        isEQPposter = true;
                    }
                }
                if (!isEQPposter) {
                    list1.add(poster);

                }
                if (imgUrls.size() > 8) {
                    for (int j = 0; j < 8; j++) {
                        list1.add(imgUrls.get(j));
                    }

                } else {
                    list1.addAll(imgUrls);
                }
                ShareUtilse.shareImage(context, 1, list1, poster,des);
                dismissLoading();
            }
            break;
            case R.id.tv_save: {//保存
                ClipboardManager mClipboardManager = mClipboardManager =
                        (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);

                ClipData mClipData;
                mClipData = ClipData.newPlainText("test", des);
                mClipboardManager.setPrimaryClip(mClipData);
                ToastUtil.initToast(context, "文案已复制");
                List<String> list = new ArrayList<>();
                boolean isEQPposter = false;

                for (int j = 0; j < imgUrls.size(); j++) {
                    if (imgUrls.get(j).equals(poster)) {
                        isEQPposter = true;
                    }
                }
                if (!isEQPposter) {
                    list.add(poster);

                }
                list.addAll(imgUrls);

                LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + list.size() + "张");
                loadingDialog.show(getActivity().getFragmentManager(), "0");

                saveImageForRecursive(list, list.size(), loadingDialog);

            }
            break;

        }


    }

    public void saveImageForRecursive(final List<String> img, final int imgSize, final LoadingSaveDialog loadingSaveDialog) {
        final List<String> imgs = new ArrayList<>();//递归保存
        imgs.addAll(img);
        if (loadingSaveDialog != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadingSaveDialog.setLoadingTips("已保存" + (imgSize - imgs.size() + 1) + "/" + imgSize + "张");
                }
            });

        }
        if (imgs.size() != 0) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    saveImageToSdCard(context, imgs.get(0), true);

                    imgs.remove(0);
                    saveImageForRecursive(imgs, imgSize, loadingSaveDialog);
                }
            }
            ).start();
        } else {

            if (loadingSaveDialog != null) {

                loadingSaveDialog.dismiss();
            }
            Looper.prepare();
            String fileName;
            if (Build.BRAND.equals("Xiaomi")) { // 小米手机
                fileName = "/DCIM/Camera/";
            } else {  // Meizu 、Oppo
                fileName = "/DCIM/Camera/";
            }
            ToastUtil.initToast(context, "图文保存至" + fileName);

            ToastUtil.initToast(context, "图文保存成功！快去发朋友圈推广吧~");
            Looper.loop();
        }

    }

    //根据网络图片url路径保存到本地
    public final File saveImageToSdCard(Context context, String image, boolean isxiangce) {
        boolean success = false;
        File file = null;
        try {
            if (isxiangce) {
                file = createXiangCeImageFile(context);
            } else {
                file = createStableImageFile(context);

            }

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));//path_export是你导出的文件路径


        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }

    //创建相册
    public File createXiangCeImageFile(Context context) throws IOException {
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    //创建本地保存路径
    public File createStableImageFile(Context context) throws IOException {

        i++;
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }

    }

    /**
     * @param flag 0分享给微信好友  1分享到朋友圈
     */
    public void shareImage(final Context context, final int flag, final List<String> images, final String isHightWXNeedShare) {

        //判断是否安装微信，如果没有安装微信 又没有判断就直达微信分享是会挂掉的
        IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.ID.WeChat_APP_ID, true);
        api.registerApp(Constant.ID.WeChat_APP_ID);
        if (!api.isWXAppInstalled()) {//未安装微信
            ToastUtil.initToast(context, "您未安装微信");

        } else {
            final List<File> files = new ArrayList<>();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    //这一步一定要clear,不然分享了朋友圈马上分享好友图片就会翻倍
                    files.clear();

                    try {
                        Intent intent = new Intent();
                        ComponentName comp;
                        if (flag == 0) {//flag 0分享给微信好友
                            for (int i = 0; i < images.size(); i++) {
                                File file = saveImageToSdCard(context, images.get(i), false);
                                files.add(file);
                            }
                            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
                            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                            ArrayList<Uri> imageUris = new ArrayList<Uri>();
                            for (File f : files) {
                                imageUris.add(Uri.fromFile(f));
                            }
                            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                        } else {//1分享到朋友圈
                            if (AppContext.isHightWX) {
                                File file = saveImageToSdCard(context, isHightWXNeedShare, false);
                                intent.setAction(Intent.ACTION_SEND);
                                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));


                            } else {
                                for (int i = 0; i < images.size(); i++) {
                                    File file = saveImageToSdCard(context, images.get(i), false);
                                    files.add(file);
                                }
                                intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                                ArrayList<Uri> imageUris = new ArrayList<Uri>();
                                for (File f : files) {
                                    imageUris.add(Uri.fromFile(f));
                                }

                                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                            }
                            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
                            intent.putExtra("Kdescription", "分享朋友圈的图片说明");
                        }
                        intent.setComponent(comp);
                        intent.setType("image/*");

                        context.startActivity(intent);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }


    }


}
